<?php
namespace My\Controller;

use Utuo\BackgroundController;
use Think\Model;

class ProductGoodsController extends BackgroundController {
	
	// 状态
	private $status = array(
			0 => '下架',
			1 => '上架'
	);
	
	private $isLows = array(
			0 => '非促销',
			1 => '促销'
	);
	
	private $isShipping = array(
			0 => '自担运费',
			1 => '免运费'
	);
	
	// 栏目id
	private $catId;
	
	public function _initialize() {
		$this->catId = $catId = I('cat_id', 0, 'intval');
		$this->setControllerTitle("商品管理");
		$this->setActionTitle(array(
			'index' => "商品列表",
			'modify' => "编辑商品",
			'setAttribute' => "设置商品属性",
			'groupBuySetting' => '团购设置',
			'add' => "添加商品",
			'recycle' => "回收站"
		));
		$this->setActionTitle('list', '商品列表', "cat_id=$catId");
		$this->setActionTitle('add', '添加商品', "cat_id=$catId");
		$this->setActionTitle('recycle', '回收站', "cat_id=$catId");
		$this->setActionNav('index,add,recycle');
		$this->assign('cat_id', $catId);
	}
	
	// 商品列表
	public function indexAction() {
		layout("ProductGoods/layout");
		$data = D("ProductCategory")->where(array('cid'=>$this->aid, 'is_deleted'=>0))->order('sort')->select();
		$productCategoryJSON = $this->getSimpleJSON($data);
		$this->assign("productCategoryJSON", $productCategoryJSON);
		$this->display();
	}
	
	public function listAction() {
		$this->resetHeader()->getProductGoodsList(0);
	}
	
	// 添加商品页面
	public function addAction() {
		$this->resetHeader();
		$d = D("ProductGoods");
		$this->assign('is_shipping', $this->getRadio('is_shipping', $this->isShipping));
		$this->assign('priceAttributes', $this->getOption($d->priceAttributes, null, '==请选择=='));
		$this->assign('status', $this->getRadio('status', $this->status, 1));
		$this->display();
	}
	
	// 添加商品
	public function addPostAction() {
		$dProductGoods = D('ProductGoods');
		$dProductGoodsConfig = D('ProductGoodsConfig');
		if ($dProductGoods->create() && $dProductGoodsConfig->create()) {
			$dProductGoods->cid = $this->aid;
			$dProductGoods->page_title = $dProductGoods->name;
			$dProductGoods->page_keywords = $dProductGoods->name;
			if ($id = $dProductGoods->add() and $dProductGoodsConfig->id = $id) {
				$dProductGoodsConfig->cid = $this->aid;
				$dProductGoodsConfig->add() and $this->ajaxSuccess('添加商品成功');
				$this->ajaxError('修改商品成功');
			}
		} else {
			$this->ajaxError('创建数据失败');
		}
	}
	
	// 修改商品
	public function modifyAction() {
		$this->resetHeader();
		$id = I("id", 0, "intval");
		$dProductGoods = D('ProductGoods');
		$productGoods = $dProductGoods->alias('this0')->join("__PRODUCT_GOODS_CONFIG__ this1 on this1.id = this0.id", 'LEFT')->where("this0.id=$id")->find();
		/*获得类目路径*/
		$classId = $productGoods['class_id'];
		$d = D('ProductClass');
		$path = "";
		while($classId) { $path=$classId.','.$path;	$class = $d->find($classId) and $classId = $class['pid']; }
		/*获得类目所有属性*/
		$productGoods['classPath'] = trim($path, ",");
		$productGoods['is_low'] = $this->getRadio('is_low', $this->isLows, $productGoods['is_low']);
		$productGoods['status'] = $this->getRadio('status', $this->status, $productGoods['status']);
		$productGoods['is_shipping'] = $this->getRadio('is_shipping', $this->isShipping, $productGoods['is_shipping']);
		$productGoods['shipping'] = explode("|", $productGoods['shipping_cfg']);
		$productGoods['priceAttributes'] = $this->getOption($dProductGoods->priceAttributes, $productGoods['price_attribute'], '==请选择==');
		$this->assign("product", $productGoods);
		$this->display();
	}
	
	
	
	// 修改商品
	public function modifyPostAction() {
		$dProductGoods = D('ProductGoods');
		$dProductGoodsConfig = D('ProductGoodsConfig');
		if ($dProductGoods->create() and $configData = $dProductGoodsConfig->create()) {
			if($dProductGoods->class_id) {
				/*是否可选*/
				$productClass = M("ProductClass")->find($dProductGoods->class_id);
				$productClass['type'] != \Admin\Model\ProductClassModel::TYPE_ALWAYS_SELECTABLE and $productClass['has_child']!=0 and $this->ajaxError('当前选择的类目无效');
			}
			$dProductGoods->cid = $this->aid;
			if (false !== $dProductGoods->save()) {
				(count($configData)==1 or false !== $dProductGoodsConfig->save()) and $this->ajaxSuccess();
				$this->ajaxError("修改商品失败");
			}
		} else {
			$this->ajaxError('创建数据失败');
		}
	}
	
	// 设置商品属性
	public function setAttributeAction() {
		$this->resetHeader();
		$id = I("id", 0, "intval");
		$dProductGoods = D('ProductGoods');
		$productGoods = $dProductGoods->alias('this0')->join("__PRODUCT_GOODS_CONFIG__ this1 on this1.id = this0.id", 'LEFT')->where("this0.id=$id")->find();
		$options = toArray($productGoods['attribute_values'], 1);
		$productGoods['attrHtml'] = $this->getAttributesHtml($productGoods['class_id'], $id, $options);
		$attributeStandard = $dProductGoods->getProductStandardAttribute($id);
		$this->assign("attributeStandard", empty($attributeStandard)?"null":json_encode($attributeStandard));
		$this->assign("productGoods", $productGoods);
		$this->display();
	}
	
	// 回收站
	public function recycleAction() {
		$this->resetHeader()->getProductGoodsList(1);
	}
	
	// 商品列表
	public function getProductGoodsList($is_deleted = 0) {
		$page = $this->getPage ();
		$pagesize = $this->getPageSize ();
		$d = D ( 'ProductGoods' );
		$condition = array (
				'cid' => $this->aid,
				'is_deleted' => $is_deleted,
				'cat_id' => $this->catId
		);
		$productGoodsList = $d->where ( $condition )->limit ( $pagesize )->page ( $page )->order ( 'id DESC' )->select ();
		$productGoodsCount = $d->where ( $condition )->count ();
		foreach ($productGoodsList as &$v) {
			$v['statusName'] = $d->status[$v['status']];
			$v['priceAttribute'] = empty($v['price_attribute'])?'':"/".$d->priceAttributes[$v['price_attribute']];
		}
		$this->assign ( 'productLists', $productGoodsList );
		$this->showPage ( $productGoodsCount, $pagesize );
		$this->display();
	}
	
	// 移除
	public function removePostAction() {
		$this->ajaxRemove();
	}
	
	// 恢复
	public function restorePostAction() {
		$this->ajaxRestore();	
	}
	
	// 彻底删除
	public function deletePostAction() {
		$this->ajaxDelete();
	}
	
	// 设置状态
	public function setStatusPostAction() {
		$this->ajaxSetStatus();
	}
	
	// 获取子类目
	public function classPostAction() {
		$id = I('id', 0, 'intval');
		$d = D('ProductClass');
		$data = $d->where(array('pid'=>$id, 'is_deleted'=> 0))->order('sort')->select();
		foreach($data as &$v) $v['isParent'] = true;
		$this->ajaxSuccess('', $data);
	}
	
	// 获得属性html
	public function getAttributesHtmlPost() {
		$id = I('id', 0, 'intval');
		$classId = I("class_id", 0, 'intval');
		$this->ajaxSuccess('', $this->getAttributesHtml($classId, $id, null));
	}
	
	/**
	 * 获取多选表单
	 *
	 * @param string $name
	 * @param array $options
	 * @param string $default
	 * @return string
	 */
	protected function getCheckBox($name, $options, $default = array()) {
		$default == null and $default = array();
		!is_array($default) and $default = array($default);
		$ret = array();
		$i = 0;
		foreach ($options as $k => $v) {
			$checked = !is_null($default) && in_array($k, $default) == $k ? " checked='checked'" : '';
			$subject = "<label title='$v'><input type='checkbox' name='$name' id='{$name}_$k' value='$k'$checked> $v</label>";
			$ret[] = str_replace("{:index}", $i, $subject);
			$i++;
		}
		return implode("\n", $ret);
	}
	
	/**
	 * 获得类目所有属性选择列表
	 * 接收时的格式: 
	 *    array(
	 *      0 => array(
	 *        'id' => 属性id,
	 *        'value' => array(属性值1, 属性值2...),
	 *        'name' => array(名称1, 名称2...),
	 *      )
	 *    )
	 * @param unknown $classId 类目id
	 * @param unknown $defaultValues 商品多个属性已选择的值  array('属性一id'=>array('已选值1','已选值2'), ... ...)
	 * @return multitype:string
	 */
	private function getAttributesHtml($classId, $productGoodsId, $defaultValues) {
		$attrHtml = array();
		$d = D("ProductGoods");
		$attributeLists = M('ProductAttribute')->where("class_id={$classId}")->order("is_standard")->select();
		foreach ($attributeLists as $attr) {
			$options = toArray($attr['values'], 0, 0); // 类目属性值表
			$inputHidden = "<input t='attr_id' name='attribute_values[{$attr['id']}][id]' value='{$attr['id']}' type='hidden' />";
			$isStandardInputHidden = "<input t='is_standard' name='attribute_values[{$attr['id']}][is_standard]' value='{$attr["is_standard"]}' type='hidden' />";
			$isMultiselect = "<input t='is_multiselect' name='attribute_values[{$attr['id']}][multiselect]' value='{$attr["multiselect"]}' type='hidden' />";
			$default = $defaultValues && isset($defaultValues[$attr['id']])? $defaultValues[$attr['id']] : null;
			/*生成复选框*/
			if($attr["multiselect"]) // 多选属性
				$attrHtml[$attr['name']] = $this->getCheckBox("attribute_values[{$attr['id']}][value][{:index}]", $options, $default);
			else
				$attrHtml[$attr['name']] = $this->getRadio("attribute_values[{$attr['id']}][value][0]", $options, $default ? $default[0] : $default);
			$attrHtml[$attr['name']].=$inputHidden.$isStandardInputHidden.$isMultiselect;
		}
		return $attrHtml;
	}
	
	// 重置导航
	private function resetHeader() {
		$this->setActionNav(false)->setActionNav('list,add,recycle');
		return $this;
	}

}